package com.junmoo.www.auth.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.junmoo.www.entity.SysUser;
import com.junmoo.www.tool.JwtUtils;
import com.junmoo.www.tool.RespUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.ServerAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 登录成功处理类
 */
@Component
@Slf4j
public class CloudAuthenticationSuccessHandler  implements ServerAuthenticationSuccessHandler {
    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public Mono<Void> onAuthenticationSuccess(WebFilterExchange exchange, Authentication authentication)  {
        log.info("-------SuccessHandler-----------"+ JSON.toJSONString(authentication));
        ServerHttpResponse response = exchange.getExchange().getResponse();
        // 组装JWT
        SysUser user = (SysUser)authentication.getDetails();
        String userJson = JSONObject.toJSONString(user);
        String token = JwtUtils.generateToken(userJson);
        String refresh_token = JwtUtils.generateToken(userJson,3*60*60L);
        // redis存储
        redisTemplate.delete(user.getUsername());
        Map<String,Object> map = new HashMap();
        map.put("token",refresh_token);
        map.put("user",JSONObject.toJSONString(user));
        map.put("role",JSONObject.toJSONString(user.getRoles()));
        map.put("auth",JSONObject.toJSONString(user.getAuthorities()));
        redisTemplate.opsForHash().putAll(user.getUsername(),map);
        redisTemplate.expire(user.getUsername(),2, TimeUnit.HOURS);

        // 封装返回参数
        Map<String,Object> resultData = new HashMap<>();
        resultData.put("code","200");
        resultData.put("msg", "登录成功");
        resultData.put("token",token);

        return RespUtil.writeMsg(response,200,resultData);
    }
}
